package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.GroupCreateRequestMessage;
import host.skiree.nettydemo.message.GroupCreateResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.factory.RoomChannelFactory;
import host.skiree.nettydemo.server.dto.impl.UserChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.Set;

/**
 * @author anorak
 */
public class GroupCreate implements MessageHandler {
    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        GroupCreateRequestMessage groupCreateRequestMessage = (GroupCreateRequestMessage) message;
        String groupName = groupCreateRequestMessage.getGroupName();
        Set<String> names = groupCreateRequestMessage.getMembers();
        System.out.println(groupCreateRequestMessage);
        if (RoomChannelFactory.getInstance().createGroup(groupName, names) == null){
            System.out.println("执行了");
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "该房间已存在"));
        }else {
            // 创建成功
            UserChannelImpl.USER_CHANNEL_MAP.forEach( (k, v) -> {
                if (names.contains(v)){
                    k.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入 " + groupName + " 聊天组"));
                }
            });
        }
    }
}
